package tw.asap.plus.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.ResultReceiver;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.location.Poi;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.common.data.DataBufferUtils;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.places.AutocompletePrediction;
import com.google.android.gms.location.places.AutocompletePredictionBuffer;
import com.google.android.gms.location.places.Place;
import com.google.android.gms.location.places.PlaceBuffer;
import com.google.android.gms.location.places.PlaceLikelihood;
import com.google.android.gms.location.places.PlaceLikelihoodBuffer;
import com.google.android.gms.location.places.Places;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import tw.asap.plus.R;
import tw.asap.plus.common.ConstValue;
import tw.asap.plus.entity.LocationBean;
import tw.asap.plus.service.FetchAddressIntentService;
import tw.asap.plus.ui.AsapBaseActivity;
import tw.asap.plus.utils.LocateUtil;
import tw.asap.plus.utils.SPUtil;
import tw.asap.plus.utils.ScreenUtil;
import tw.asap.plus.utils.T;
import tw.asap.plus.utils.Toaster;

/**
 * Description:
 * Created:      [15/11/19]
 * Author:       [Yang]
 **/
public class GeoActivity extends AsapBaseActivity implements View.OnClickListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, AdapterView.OnItemClickListener {


    private static final String TAG = "GeoActivity";
    @InjectView(R.id.ll_navigation_left)
    ImageView llNavigationLeft;
    @InjectView(R.id.tv_search_view)
    EditText tvSearchView;
    @InjectView(R.id.layout_navigation_header)
    RelativeLayout layoutNavigationHeader;
    @InjectView(R.id.history_title)
    TextView historyTitle;
    @InjectView(R.id.history_layout)
    LinearLayout historyLayout;
    @InjectView(R.id.ll_default_view)
    LinearLayout llDefaultView;
    @InjectView(R.id.list_predict_location)
    ListView listPredictLocation;
    @InjectView(R.id.ll_locate_current_position)
    LinearLayout llLocateCurrentPosition;
    @InjectView(R.id.progress_bar)
    ProgressBar progressBar;
    @InjectView(R.id.icon_location)
    ImageView iconLocation;
    @InjectView(R.id.status)
    TextView status;
    @InjectView(R.id.search_progress_bar)
    ProgressBar searchProgressBar;
    private GoogleApiClient mGoogleApiClient;
    LatLngBounds BOUNDS_GREATER_SYDNEY = null;
    double gap = 1;
    private Location mLastLocation;
    private boolean mAddressRequested;
    private AddressResultReceiver mResultReceiver;
    //    private String mAddressOutput;
    private Address mAddress;
    ArrayList<AutocompletePrediction> predictionArrayList = new ArrayList<>();
    SimpleLocationAdapter adapter;
    String currentWords = "";
    private Place mPlace;
    public static final int MAX_COUNT_GET_LOCATION = 3;
    int tryTime = 0;

    //声明AMapLocationClient类对象
    public AMapLocationClient mLocationClient = null;
    //声明定位回调监听器
    public AMapLocationListener mLocationListener = null;
    //声明mLocationOption对象
    public AMapLocationClientOption mLocationOption = null;
    private LocationBean mLocation;

    public LocationClient mBaiduLocationClient = null;
    public BDLocationListener mBaiduListener = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_location);
        ButterKnife.inject(this);
        Location mLastLocation = getIntent().getParcelableExtra("LOCATION");
        if (mLastLocation != null) {
            BOUNDS_GREATER_SYDNEY = new LatLngBounds(
                    new LatLng(mLastLocation.getLatitude() - gap, mLastLocation.getLongitude() - gap),
                    new LatLng(mLastLocation.getLatitude() + gap, mLastLocation.getLongitude() + gap));
        }
        initGoogleApiClient();
//        initAmapApiClient();
        initBaiduApiClient();
        setUpHeadView();
    }

    private void setUpHeadView() {
        tvSearchView.addTextChangedListener(searchWatcher);
        tvSearchView.setOnEditorActionListener((v, actionId, event) -> {
            switch (actionId) {
                case EditorInfo.IME_ACTION_SEARCH:
                    return true;
            }
            return false;
        });

        tvSearchView.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    llDefaultView.setVisibility(View.GONE);
                    listPredictLocation.setVisibility(View.VISIBLE);
                } else {
                    llDefaultView.setVisibility(View.VISIBLE);
                    listPredictLocation.setVisibility(View.GONE);
                }
            }
        });
        adapter = new SimpleLocationAdapter(this);
        listPredictLocation.setAdapter(adapter);
        listPredictLocation.setOnItemClickListener(this);

        ArrayList<String> historyKeywords = (ArrayList<String>) SPUtil.getInstance(this).
                getSerializable(ConstValue.Sp.KEY_WORDS, new TypeToken<ArrayList<String>>() {
                }.getType());

        if (historyKeywords != null && historyKeywords.size() > 0) {
            for (String keywords : historyKeywords) {
                TextView view = (TextView) LayoutInflater.from(this).inflate(R.layout.item_keywords, null);
                LinearLayout.LayoutParams params =
                        new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ScreenUtil.dip2px(this, 48));
                view.setText(keywords);
                view.setVisibility(View.VISIBLE);
                historyLayout.addView(view, params);
                view.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        tvSearchView.requestFocus();
                        tvSearchView.setText(keywords);
//                        searchProgressBar.setVisibility(View.VISIBLE);
//                        searchKeywords(keywords);
//                        currentWords = keywords;
                    }
                });
            }
        }
    }

    private void searchKeywords(String s) {
        new Thread(() -> {
            if (mGoogleApiClient.isConnected()) {
                PendingResult<AutocompletePredictionBuffer> results =
                        Places.GeoDataApi.getAutocompletePredictions(mGoogleApiClient, s,
                                BOUNDS_GREATER_SYDNEY, null);

                AutocompletePredictionBuffer autocompletePredictions = results
                        .await(60, TimeUnit.SECONDS);

                // Confirm that the query completed successfully, otherwise return null
                final Status status = autocompletePredictions.getStatus();
                if (!status.isSuccess()) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(GeoActivity.this, "Error contacting API: " + status.toString(),
                                    Toast.LENGTH_SHORT).show();
                        }
                    });
                    Log.e(TAG, "Error getting autocomplete prediction API call: " + status.toString());
                    autocompletePredictions.release();
                    return;
                }

                Log.i(TAG, "Query completed. Received " + autocompletePredictions.getCount()
                        + " predictions.");
                // Freeze the results immutable representation that can be stored safely.
                if (predictionArrayList != null) {
                    predictionArrayList.clear();
                    predictionArrayList.addAll(DataBufferUtils.freezeAndClose(autocompletePredictions));
                } else {
                    predictionArrayList = DataBufferUtils.freezeAndClose(autocompletePredictions);
                }
                handler.sendEmptyMessage(0x01);

                for (AutocompletePrediction prediction : predictionArrayList) {
                    Log.i(TAG, "prediction:" + prediction.getDescription());
                    //https://developers.google.com/places/place-id
                }
            } else {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        Toaster.s(GeoActivity.this, "无法链接到GooglePlaceService");
                    }
                });
            }
        }).start();

    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0x01:
                    searchProgressBar.setVisibility(View.GONE);
                    adapter.notifyDataSetChanged();
                    break;
            }
        }
    };

    private void initGoogleApiClient() {

        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addApi(Places.GEO_DATA_API)
                .addApi(Places.PLACE_DETECTION_API)
                .addOnConnectionFailedListener(this)
                .build();
    }

    private void initAmapApiClient() {
        mLocationListener = new AMapLocationListener() {
            @Override
            public void onLocationChanged(AMapLocation aMapLocation) {
                if (aMapLocation != null) {
                    if (aMapLocation.getErrorCode() == 0) {
                        //定位成功回调信息，设置相关消息
                        T.i("AmapLocation: " + aMapLocation.toString());

                        mLocation = new LocationBean();
                        mLocation.latitude = String.valueOf(aMapLocation.getLatitude());
                        mLocation.longitude = String.valueOf(aMapLocation.getLongitude());
                        mLocation.address = aMapLocation.getAddress();
                        String address = aMapLocation.getExtras().getString("desc");
                        if (address != null && address.contains(" ")) {
                            String[] spliteAddr = address.split(" ");
                            mLocation.name = spliteAddr[spliteAddr.length - 2].concat(spliteAddr[spliteAddr.length - 1]);
                        }else {
                            mLocation.name = aMapLocation.getAddress();
                        }
                        displayAddressOutput(2);
                        mAddressRequested = true;
                        mLocationClient.stopLocation();
                    } else {
                        //显示错误信息ErrCode是错误码，errInfo是错误信息，详见错误码表。
                        Log.e("AmapError", "location Error, ErrCode:"
                                + aMapLocation.getErrorCode() + ", errInfo:"
                                + aMapLocation.getErrorInfo());
                    }
                }
            }
        };
        //初始化定位
        mLocationClient = new AMapLocationClient(getApplicationContext());
        //设置定位回调监听
        mLocationClient.setLocationListener(mLocationListener);
        //初始化定位参数
        mLocationOption = new AMapLocationClientOption();
        //设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设置是否返回地址信息（默认返回地址信息）
        mLocationOption.setNeedAddress(true);
        //设置是否只定位一次,默认为false
        mLocationOption.setOnceLocation(false);
        //设置是否强制刷新WIFI，默认为强制刷新
        mLocationOption.setWifiActiveScan(true);
        //设置是否允许模拟位置,默认为false，不允许模拟位置
        mLocationOption.setMockEnable(false);
        //设置定位间隔,单位毫秒,默认为2000ms
        mLocationOption.setInterval(20000);
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
    }
    private void initBaiduApiClient() {
        mBaiduLocationClient = new LocationClient(getApplicationContext());     //声明LocationClient类
        mBaiduListener = new BDLocationListener() {
            @Override
            public void onReceiveLocation(BDLocation bdLocation) {
                StringBuffer sb = new StringBuffer(256);
                sb.append("time : ");
                sb.append(bdLocation.getTime());
                sb.append("\nerror code : ");
                sb.append(bdLocation.getLocType());
                sb.append("\nlatitude : ");
                sb.append(bdLocation.getLatitude());
                sb.append("\nlontitude : ");
                sb.append(bdLocation.getLongitude());
                sb.append("\nradius : ");
                sb.append(bdLocation.getRadius());
                if (bdLocation.getLocType() == BDLocation.TypeGpsLocation) {// GPS定位结果
                    sb.append("\nspeed : ");
                    sb.append(bdLocation.getSpeed());// 单位：公里每小时
                    sb.append("\nsatellite : ");
                    sb.append(bdLocation.getSatelliteNumber());
                    sb.append("\nheight : ");
                    sb.append(bdLocation.getAltitude());// 单位：米
                    sb.append("\ndirection : ");
                    sb.append(bdLocation.getDirection());// 单位度
                    sb.append("\naddr : ");
                    sb.append(bdLocation.getAddrStr());
                    sb.append("\ndescribe : ");
                    sb.append("gps定位成功");

                } else if (bdLocation.getLocType() == BDLocation.TypeNetWorkLocation) {// 网络定位结果
                    sb.append("\naddr : ");
                    sb.append(bdLocation.getAddrStr());
                    //运营商信息
                    sb.append("\noperationers : ");
                    sb.append(bdLocation.getOperators());
                    sb.append("\ndescribe : ");
                    sb.append("网络定位成功");
                } else if (bdLocation.getLocType() == BDLocation.TypeOffLineLocation) {// 离线定位结果
                    sb.append("\ndescribe : ");
                    sb.append("离线定位成功，离线定位结果也是有效的");
                } else if (bdLocation.getLocType() == BDLocation.TypeServerError) {
                    sb.append("\ndescribe : ");
                    sb.append("服务端网络定位失败，可以反馈IMEI号和大体定位时间到loc-bugs@baidu.com，会有人追查原因");
                } else if (bdLocation.getLocType() == BDLocation.TypeNetWorkException) {
                    sb.append("\ndescribe : ");
                    sb.append("网络不同导致定位失败，请检查网络是否通畅");
                } else if (bdLocation.getLocType() == BDLocation.TypeCriteriaException) {
                    sb.append("\ndescribe : ");
                    sb.append("无法获取有效定位依据导致定位失败，一般是由于手机的原因，处于飞行模式下一般会造成这种结果，可以试着重启手机");
                }
                sb.append("\nlocationdescribe : ");
                sb.append(bdLocation.getLocationDescribe());// 位置语义化信息
                List<Poi> list = bdLocation.getPoiList();// POI数据
                if (list != null) {
                    sb.append("\npoilist size = : ");
                    sb.append(list.size());
                    for (Poi p : list) {
                        sb.append("\npoi= : ");
                        sb.append(p.getId() + " " + p.getName() + " " + p.getRank());
                    }
                }
                Log.i("BaiduLocationApiDem", sb.toString());

                if (bdLocation.getLocType() == BDLocation.TypeNetWorkLocation || bdLocation.getLocType() == BDLocation.TypeOffLineLocation
                        || bdLocation.getLocType() == BDLocation.TypeGpsLocation) {

                    mLocation = new LocationBean();
                    mLocation.latitude = String.valueOf(bdLocation.getLatitude());
                    mLocation.longitude = String.valueOf(bdLocation.getLongitude());
                    mLocation.address = bdLocation.getAddrStr();
//                    List<Poi> poiList = bdLocation.getPoiList();
//                    if (poiList != null && poiList.size() > 0) {// POI数据
//                        mLocation.name = poiList.get(0).getName();
//                    } else {
//                        mLocation.name = bdLocation.getAddrStr();
//                    }
                    mLocation.name = bdLocation.getAddrStr();
                    displayAddressOutput(2);
                    mAddressRequested = true;
                    mBaiduLocationClient.stop();
                }
            }
        };
        mBaiduLocationClient.registerLocationListener(mBaiduListener);    //注册监听函数
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy
        );//可选，默认高精度，设置定位模式，高精度，低功耗，仅设备
        option.setCoorType("gcj02");//可选，默认gcj02，设置返回的定位结果坐标系
        int span = 2000;
        option.setScanSpan(span);//可选，默认0，即仅定位一次，设置发起定位请求的间隔需要大于等于1000ms才是有效的
        option.setIsNeedAddress(true);//可选，设置是否需要地址信息，默认不需要
        option.setOpenGps(true);//可选，默认false,设置是否使用gps
        option.setLocationNotify(true);//可选，默认false，设置是否当gps有效时按照1S1次频率输出GPS结果
        option.setIsNeedLocationDescribe(true);//可选，默认false，设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于“在北京天安门附近”
        option.setIsNeedLocationPoiList(true);//可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到
        option.setIgnoreKillProcess(false);//可选，默认false，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认杀死
        option.SetIgnoreCacheException(false);//可选，默认false，设置是否收集CRASH信息，默认收集
        option.setEnableSimulateGps(false);//可选，默认false，设置是否需要过滤gps仿真结果，默认需要
        mBaiduLocationClient.setLocOption(option);
    }

    @Override
    public void onConnected(Bundle bundle) {

    }

    TextWatcher searchWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            if (!TextUtils.isEmpty(s)) {
                searchProgressBar.setVisibility(View.VISIBLE);
                searchKeywords(s.toString());
                currentWords = s.toString();
            }
        }
    };


    @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    public void onClick(View v) {

    }

    @OnClick(R.id.ll_navigation_left)
    protected void onBackClick() {
        finish();
    }

    @OnClick(R.id.ll_locate_current_position)
    protected void locateCurrentPosition() {
        if (mGoogleApiClient.isConnected()) {

            status.setText("正在定位，请稍后...");
            iconLocation.setVisibility(View.GONE);
            progressBar.setVisibility(View.VISIBLE);

            mBaiduLocationClient.start();
//            mLocationClient.startLocation();
//            getMyLocation();
//            getMyPlace();

        } else {
            Toaster.s(GeoActivity.this, "无法链接到GooglePlaceService");
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(mLocationClient!=null){
            mLocationClient.onDestroy();
        }
    }

    private void getMyPlace() {
        PendingResult<PlaceLikelihoodBuffer> result = Places.PlaceDetectionApi
                .getCurrentPlace(mGoogleApiClient, null);
        result.setResultCallback(new ResultCallback<PlaceLikelihoodBuffer>() {
            @Override
            public void onResult(PlaceLikelihoodBuffer likelyPlaces) {
                for (PlaceLikelihood placeLikelihood : likelyPlaces) {
                    Log.i(TAG, String.format("Place '%s' has likelihood: %g",
                            placeLikelihood.getPlace().getName(),
                            placeLikelihood.getLikelihood()));
                }
                if (likelyPlaces.getCount() > 0) {
                    Place currentPlace = likelyPlaces.get(0).getPlace().freeze();
                    mPlace = currentPlace;
                    SPUtil.getInstance(GeoActivity.this).save(ConstValue.Sp.LAT, String.valueOf(currentPlace.getLatLng().latitude));
                    SPUtil.getInstance(GeoActivity.this).save(ConstValue.Sp.LNG, String.valueOf(currentPlace.getLatLng().longitude));
                    displayAddressOutput(0);
                } else {
                    Toaster.s(GeoActivity.this, "获取位置信息失败");
                }
                likelyPlaces.release();
            }
        });
    }

    private void getMyLocation() {
        if (!mAddressRequested && tryTime < MAX_COUNT_GET_LOCATION) {
            mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
            tryTime++;
            if (mLastLocation != null) {
                T.i("location+++++++++++ : " + String.valueOf(mLastLocation.getLatitude()),
                        String.valueOf(mLastLocation.getLongitude()));
                mLastLocation = LocateUtil.transformFromWGSToGCJ(mLastLocation);

                SPUtil spUtil = SPUtil.getInstance(this);
                spUtil.save(ConstValue.Sp.LAT, String.valueOf(mLastLocation.getLatitude()));
                spUtil.save(ConstValue.Sp.LNG, String.valueOf(mLastLocation.getLongitude()));

                if (!Geocoder.isPresent()) {
                    Toast.makeText(this, R.string.no_geocoder_available,
                            Toast.LENGTH_LONG).show();
                    return;
                }
                startIntentService();
            } else {
                getMyLocation();
            }
        }
    }

    protected void startIntentService() {

        if (mResultReceiver == null) {
            mResultReceiver = new AddressResultReceiver(new Handler());
        }
        Intent intent = new Intent(this, FetchAddressIntentService.class);
        intent.putExtra(ConstValue.RECEIVER, mResultReceiver);
        intent.putExtra(ConstValue.LOCATION_DATA_EXTRA, mLastLocation);
        startService(intent);
        mAddressRequested = true;
    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        if (connectionResult.getErrorCode() == ConnectionResult.SERVICE_MISSING) {
            Toaster.s(this, getString(R.string.google_service_miss));
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        mGoogleApiClient.connect();
    }

    @Override
    protected void onStop() {
        if (mGoogleApiClient.isConnected())
            mGoogleApiClient.disconnect();
        super.onStop();
    }

    private void displayAddressOutput(int type) {

        iconLocation.setVisibility(View.VISIBLE);
        progressBar.setVisibility(View.GONE);
        Intent intent = new Intent();
        LocationBean bean = new LocationBean();
        switch (type) {
            case 0:
                status.setText(mPlace.getName());
                bean.address = mPlace.getAddress().toString();
                bean.latitude = String.valueOf(mPlace.getLatLng().latitude);
                bean.longitude = String.valueOf(mPlace.getLatLng().longitude);
                bean.name = mPlace.getName().toString();
                break;
            case 1:

                bean.address = mAddress.getAddressLine(1);
                if(TextUtils.isEmpty(mAddress.getFeatureName()) || mAddress.getFeatureName().length()<4){
                    bean.name = bean.address;
                }else{
                    bean.name = mAddress.getFeatureName();
                }
                bean.latitude = String.valueOf(mAddress.getLatitude());
                bean.longitude = String.valueOf(mAddress.getLongitude());
                status.setText(bean.name);
                break;
            case 2:
                if(mLocation.address.contains("中国")){
                    mLocation.address = mLocation.address.replace("中国","");
                }
                if(mLocation.address.contains("台湾省")){
                    mLocation.address = mLocation.address.replace("台湾省","");
                }
                status.setText(mLocation.address);
                bean = mLocation;
                break;
        }

        intent.putExtra("LOCATION", bean);
        setResult(RESULT_OK, intent);
        finish();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        AutocompletePrediction autocompletePrediction = predictionArrayList.get(position);
        getAddressDetail(autocompletePrediction);
        saveKeywords(autocompletePrediction.getDescription());
    }

    private void saveKeywords(String keywords) {
        ArrayList<String> historyKeywords = (ArrayList<String>) SPUtil.getInstance(this).
                getSerializable(ConstValue.Sp.KEY_WORDS, new TypeToken<ArrayList<String>>() {
                }.getType());
        if (historyKeywords == null || historyKeywords.size() == 0) {
            historyKeywords = new ArrayList<>();
            historyKeywords.add(keywords);
        } else {
            if (historyKeywords.contains(keywords)) {
                return;
            }
            if (historyKeywords.size() == 5) {
                historyKeywords.remove(0);
            }
            historyKeywords.add(keywords);
        }

        SPUtil.getInstance(this).saveSerializable(ConstValue.Sp.KEY_WORDS, historyKeywords);
    }

    private void getAddressDetail(AutocompletePrediction prediction) {
        Places.GeoDataApi.getPlaceById(mGoogleApiClient, prediction.getPlaceId())
                .setResultCallback(new ResultCallback<PlaceBuffer>() {
                    @Override
                    public void onResult(PlaceBuffer places) {
                        if (places.getStatus().isSuccess()) {
                            final Place myPlace = places.get(0);
                            T.i(myPlace.toString());
                            Place newPlace = myPlace.freeze();
                            Intent intent = new Intent();
                            LocationBean locationBean = new LocationBean();
                            locationBean.address = myPlace.getName().toString();
                            locationBean.latitude = String.valueOf(myPlace.getLatLng().latitude);
                            locationBean.longitude = String.valueOf(myPlace.getLatLng().longitude);
                            locationBean.name = myPlace.getName().toString();
                            intent.putExtra("LOCATION", locationBean);
                            setResult(RESULT_OK, intent);
                            finish();
                            Log.i(TAG, "thread id:" + Thread.currentThread().getName());
                        }
                        places.release();
                    }
                });
    }


    class AddressResultReceiver extends ResultReceiver {

        public AddressResultReceiver(Handler handler) {
            super(handler);
        }

        @Override
        protected void onReceiveResult(int resultCode, Bundle resultData) {
            T.i("Google location: onReceiveResult");
            if (resultCode == ConstValue.SUCCESS_RESULT) {
                mAddress = resultData.getParcelable(ConstValue.LOCATION_ADDRESS_EXTRA);
                displayAddressOutput(1);
            } else {

            }
        }
    }

    class SimpleLocationAdapter extends BaseAdapter {

        private final Context context;

        public SimpleLocationAdapter(Context context) {
            this.context = context;
        }

        @Override
        public int getCount() {
            return predictionArrayList.size();
        }

        @Override
        public Object getItem(int position) {
            return position;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = LayoutInflater.from(context).inflate(android.R.layout.simple_list_item_1, null);
            ((TextView) view.findViewById(android.R.id.text1)).setText(predictionArrayList.get(position).getDescription());
            return view;
        }
    }
}
